'use strict';
const db = uniCloud.database();
const usersCollection = db.collection('users');

exports.main = async (event, context) => {
  const { code, userInfo } = event;
  const appid = 'wx705677046566e1a3';
  const secret = 'f34ff4e7646b1761c02b90a757b7d0e5';

  try {
    // 1. 使用code获取openid
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
    const res = await uniCloud.httpclient.request(url, {
      dataType: 'json'
    });

    if (res.status !== 200 || !res.data.openid) {
      return {
        code: -1,
        message: '获取openid失败',
        error: res.data
      };
    }

    const openid = res.data.openid;
    
    // 2. 存储或更新用户信息
    const userRes = await usersCollection.where({ openid }).get();
    
    let userData = {
      openid,
      ...userInfo,
      updateTime: Date.now()
    };
    
    if (userRes.data && userRes.data.length > 0) {
      // 用户已存在，更新信息
      await usersCollection.doc(userRes.data[0]._id).update(userData);
    } else {
      // 新用户，添加记录
      userData.createTime = Date.now();
      await usersCollection.add(userData);
    }
    
    // 3. 存储openid到本地
    //uni.setStorageSync('openid', openid);
    
    return {
      code: 0,
      message: '授权成功',
      data: {
        openid,
		expire_time: Date.now() + 3 * 24 * 60 * 60 * 1000, // 3天有效期
        userInfo
      }
    };
    
  } catch (err) {
    console.error('授权处理失败:', err);
    return {
      code: -1,
      message: '授权处理失败',
      error: err
    };
  }
};